import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class XinHeStorage {
  //用户登录状态，是否已经登录
  static const userLoginStatus = 'userLoginStatus';
  ///token
  static const accessToken  = 'accessToken';
  static const userId  = 'userId';
  ///登录成功后返回数据
  static const loginSucData = 'loginSucData';

  static const searchHistory = 'searchHistory';


  ///个人详情数据model
  static const userInfoData = 'kd_userInfoModel';



  ///用户登录成功通知事件名称
  static const KdLoginSucNoti = 'KdLoginSucNot';
  ///用户信息更新成功
  static const KdUserInfoUpdateSuc = 'KdUserInfoUpdateSuc';
  static const KdUserLogoutNoti = 'KdUserLogoutApp';
  static const KdTokenUpdate = 'KdTokenUpdate';


  static const refreshCart = 'RefreshCart';
  static const settingDefaultAddress = 'settingDefaultAddress';

  static const settingOrUpdateBankInfo = 'settingOrUpdateBankInfo';

  static const KNeedRefresh = 'needRefresh';
}

class XinHeLocalStorage {
  static Future set(String key, value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (value.runtimeType == bool) {
      prefs.setBool(key, value);
    }else if (value.runtimeType == int) {
      prefs.setInt(key, value);
    }else if (value.runtimeType == double) {
      prefs.setDouble(key, value);
    }else if (value.runtimeType == List<String>) {
      prefs.setStringList(key, value);
    } else {
      prefs.setString(key, value);
    }
  }

  static Future get(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.get(key);
  }

  static Future setJSON(String key, value) async {
    //将json数据转为json字符串
    SharedPreferences prefs = await SharedPreferences.getInstance();
    value = json.encode(value);
    prefs.setString(key, value);
  }

  static Future getJSON(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.get(key) == null) return null;
    var value = prefs.get(key);
    return json.decode(value.toString());
  }

  static Future<bool> remove(String key) async {
    //移除单个键值对
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.remove(key);
  }

  static Future<bool> clear() async {
    //移除全部缓存
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.clear();
  }
}